package io.xiyou.account2.service.impl;

import io.xiyou.account2.Account2Service;
import io.xiyou.account2.dao.mapper.AccountFreezeMapper;
import io.xiyou.account2.dao.mapper.AccountInfoMapper;
import io.xiyou.account2.service.support.HmilySupport;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.dromara.hmily.annotation.Hmily;
import org.dromara.hmily.core.concurrent.threadlocal.HmilyTransactionContextLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @ClassName：AccountInfoServiceImpl
 * @Author：西柚
 * @Date：2021/9/30 11:30 下午
 * @Versiion：1.0
 */
@Slf4j
@Service
public class AccountInfoServiceImpl implements Account2Service {

    @Autowired
    private AccountInfoMapper accountInfoMapper;
    @Autowired
    private AccountFreezeMapper accountFreezeMapper;
    @Autowired
    private HmilySupport hmilySupport;

    @Override
    @Hmily(confirmMethod = "confirmMethod", cancelMethod = "cancelMethod")
    public Boolean addAccountBalance(Long accountId, BigDecimal money) {
        //获取全局事务id
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("account2 try begin 开始执行...xid:{}", transId);
        return true;
    }

    /**
     * confirm方法
     * confirm幂等校验
     * 正式增加金额
     *
     * @param accountId
     * @param money
     */
    @Transactional
    public void confirmMethod(Long accountId, BigDecimal money) {
        //获取全局事务id
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("account2 confirm begin 开始执行...xid:{}", transId);
        if (hmilySupport.isExistConfirm(transId) > 0) {
            log.info("account2 confirm 已经执行，无需重复执行...xid:{}", transId);
            return;
        }
        //增加金额
        accountInfoMapper.addAccountBalance(accountId, money);
        //增加一条confirm日志，用于幂等
        hmilySupport.addConfirm(transId);
        log.info("account2 confirm end 结束执行...xid:{}", transId);
    }


    /**
     * 取消方法
     *
     * @param accountId
     * @param money
     */
    public void cancelMethod(Long accountId, BigDecimal money) {
        //获取全局事务id
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("account2 cancel begin 开始执行...xid:{}", transId);
    }

}
